import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import styles from './index.module.scss';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import { useDispatch } from 'react-redux';
import { LoginAction, SendCodeAction } from '@/store/action/login';
import { useEffect, useRef, useState } from 'react';
import { Toast } from 'antd-mobile';
import { useHistory } from 'react-router-dom';
import { LoactionStateType } from '@/components/AuthRoute';
export default function Login() {
  const history = useHistory();
  const dispatch = useDispatch();
  const [isSendtime, setIsSendtime] = useState(0);
  useEffect(() => {
    return () => {
      clearInterval(TimeIdref.current);
    };
  }, []);
  const TimeIdref = useRef(-1);
  /** 发送验证码事件 */
  const handleSendCode = () => {
    if (formik.errors.mobile) return;
    if (isSendtime > 0) return;
    Toast.show('发送验证码成功!');
    setIsSendtime(60);
    dispatch(SendCodeAction(formik.values.mobile));
    TimeIdref.current = window.setInterval(() => {
      setIsSendtime((isSendtime) => {
        if (isSendtime === 1) clearInterval(TimeIdref.current);
        return isSendtime - 1;
      });
    }, 1000);
  };

  const formik = useFormik({
    initialValues: {
      mobile: '',
      code: '',
    },
    onSubmit: async (values) => {
      await dispatch(LoginAction(values));
      Toast.show({
        icon: 'success',
        content: '登录成功',
      });
      /**  处理重定向登录界面时登录后的页面跳转 */
      const { from = '/' } = (history.location.state ||
        {}) as LoactionStateType;
      history.replace(from);
    },
    validationSchema: Yup.object().shape({
      mobile: Yup.string()
        .required('手机号码不能为空')
        .matches(
          /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
          '手机号格式错误'
        ),
      code: Yup.string()
        .required('请输入六位验证码')
        .matches(/^\d{6}$/, '请输入六位验证码'),
    }),
  });

  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          {/* 手机号输入框 */}
          <Input
            placeholder="请输入手机号"
            name="mobile"
            value={formik.values.mobile}
            maxLength={11}
            className="mobile"
            onChange={formik.handleChange}
            ErrorMsg={formik.touched.mobile ? formik.errors.mobile : ''}
            onBlur={formik.handleBlur}
            autoComplete="off"
            type="text"
          ></Input>

          {/* 短信验证码输入框 */}
          <Input
            placeholder="请输入验证码"
            name="code"
            autoComplete="off"
            type="text"
            maxLength={6}
            onChange={formik.handleChange}
            extra={
              <span onClick={handleSendCode}>
                {!isSendtime ? '获取验证码' : `${isSendtime}秒后获取`}
              </span>
            }
            value={formik.values.code}
            onBlur={formik.handleBlur}
            ErrorMsg={formik.touched.code ? formik.errors.code : ''}
          ></Input>

          {/* 登录按钮 */}
          <button
            type="submit"
            className="login-btn"
            disabled={!formik.isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  );
}
